package main

import (
	"crypto/sha1"
	"fmt"
	"github.com/xtaci/kcp-go/v5"
	"go.uber.org/atomic"
	"golang.org/x/crypto/pbkdf2"
	"io"
	"time"
	"wths/wthsjy-im/plugins/log"
	"wths/wthsjy-im/protocol"
)

const (
	kcpKeyPassword = "___自定义密码____"
	kcpKeySalt     = "___自定义盐_____"
)

func kcpBlockCrypt() (kcp.BlockCrypt, error) {
	key := pbkdf2.Key([]byte(kcpKeyPassword), []byte(kcpKeySalt), 1024, 32, sha1.New)
	return kcp.NewAESBlockCrypt(key)
}

func main() {
	block, _ := kcpBlockCrypt()

	// wait for server to become ready
	time.Sleep(time.Second)

	// dial to the echo server
	if sess, err := kcp.DialWithOptions("127.0.0.1:9000", block, 10, 3); err == nil {
		for {
			data := getAuthPacketBytes()
			buf := make([]byte, len(data))
			log.Debug("kcp").Msg("sent:", data)
			if _, err := sess.Write([]byte(data)); err == nil {
				// read back the data
				if _, err := io.ReadFull(sess, buf); err == nil {
					log.Debug("kcp").Msg("recv:", string(buf))
				} else {
					log.Debug("kcp").Msg(err)
				}
			} else {
				log.Debug("kcp").Msg(err)
			}
			time.Sleep(time.Second * 30)
		}
	} else {
		log.Debug("kcp").Msg(err)
	}
}

var st = time.Now().UnixNano()
var index atomic.Int64

func getAuthPacketBytes() []byte {
	p, _ := protocol.NewConnectPacket(fmt.Sprintf("client_%d_%d", st, index.Add(1)), false)
	bs, _ := protocol.Encode(p)
	log.Debug("getAuthPacketBytes").Msg(len(bs))
	return bs
}
func getSubscribePacketBytes() []byte {
	p, _ := protocol.NewSubscribePacket([]string{"topic111"})
	//p, _ := protocol.NewSubscribePacket([]string{fmt.Sprintf("topic_%d", time.Now().UnixNano())})
	bs, _ := protocol.Encode(p)
	log.Debug("getSubscribePacketBytes").Msg(len(bs))
	return bs
}
